#!/bin/sh

list_toys() {
	toys=$(find toys/ -mindepth 1 -maxdepth 1 -type d | sed 's|toys/||' | sort)
	echo "$toys" | while read -r toy
	do
		status=$(show_item "$toy" 'latest' | head -n1 | cut -d ';' -f1)
		printf '%s;%s\n' "$status" "$toy"
	done
}

list_items() {
	toy=$1
	if [ ! -d "toys/$toy" ]
	then
		printf "n;"
	else
		printf "0;"
		items=$(find "toys/$toy" -mindepth 1 -maxdepth 1 -type d | grep -E '[0-9]+' | sed "s|toys/$toy/||" | sort -nr)
		if [ -z "$items" ]
		then
			return
		fi
		echo "$items" | while read -r item
		do
			status=$(show_item "$toy" "$item" | head -n1 | cut -d ';' -f1)
			printf '%s,%s ' "$status" "$item"
		done
	fi
}

show_item() {
	toy=$1
	item=$2
	if [ "$(podman inspect "item_${toy}_${item}" 2>/dev/null | jq -r '.[0].State.Status')" = 'exited' ]
	then
		podman inspect "item_${toy}_${item}" | jq '.[0].State.ExitCode' > "toys/$toy/$item.exit"
		podman rm "item_${toy}_${item}" >/dev/null 2>&1
	fi
	[ "$item" = 'latest' ] && item=$(find "toys/$toy/" -type d -mindepth 1 -maxdepth 1 | grep -E '[0-9]+' | sed "s|toys/$toy||" | sort -n | tail -n1 | sed "s|toys/$toy/||")
	if [ -z "$item" ] || [ ! -d "toys/$toy/$item" ]
	then
		printf 'n;'
	elif [ ! -f "toys/$toy/$item.exit" ]
	then
		printf 'r;'
		awk -f log_parser.awk "toys/$toy/$item.log"
	else
		printf '%s;' "$(cat "toys/$toy/$item.exit")"
		awk -f log_parser.awk "toys/$toy/$item.log"
	fi
}

item_artifacts() {
	toy=$1
	item=$2
	artifacts=""
	for artifactName in "toys/$toy/$item/"*
	do
		artifactName=$(printf '%s' "$artifactName" | sed "s|toys/$toy/$item/||")
		artifacts=$(printf '%s %s' "$artifacts" "$artifactName")
	done
	printf '%s' "$artifacts" | sed 's/^ //' | sed 's/^\*$//'
}

get_artifact() {
	toy=$1
	item=$2
	artifactName=$3
	if [ ! -f "toys/$toy/$item/$artifactName" ]
	then
		printf 'n;'
	else
		contentType=$(file -b -i "toys/$toy/$item/$artifactName" | cut -d ';' -f1)
		printf '0;%s;%s' "$contentType" "toys/$toy/$item/$artifactName"
	fi
}
